package com.stylefeng.guns.core.util;

public class TokenBucket {

    private int bucketNums = 100;
    private int rate = 1;
    private int nowTokens;
    private long timeStamp = getNowTime();

    private long getNowTime(){
        return System.currentTimeMillis();
    }

    private int min(int tokens){
        if (tokens < bucketNums){
            return tokens;
        }else {
            return bucketNums;
        }
    }

    public boolean getToken(){
        long nowTime = getNowTime();
        nowTokens = nowTokens + (int)((nowTime - timeStamp) * rate);
        timeStamp = nowTime;
        nowTokens = min(nowTokens);
        if (nowTokens < 1){
            return false;
        }else{
            nowTokens -= 1;
            return true;
        }
    }
}
